package edu.cuit.springboot201.dao;

import edu.cuit.springboot201.model.StudentScore;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Repository;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Repository
public class ScoreDaoFileImpl implements ScoreDao {

    private String dataFilePath;

    public ScoreDaoFileImpl() {
        ApplicationHome ah = new ApplicationHome(getClass());
        String basePath = ah.getSource().getParentFile().getAbsolutePath();//this.getClass().getClassLoader().getResource("").getPath();
        dataFilePath = basePath + "/score.data";
    }

    @Override
    public void saveScore(StudentScore score) {
        try {
            List<StudentScore> scoreList = loadScore();
            scoreList.add(score);
            File scoreFile = new File(dataFilePath);
            if (!scoreFile.exists()) {
                scoreFile.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(scoreFile);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(scoreList);
            oos.close();
            fos.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<StudentScore> loadScore() {
        try {
            File scoreFile = new File(dataFilePath);
            if (!scoreFile.exists()) {
                return new ArrayList<>();
            }
            FileInputStream fis = new FileInputStream(scoreFile);
            ObjectInputStream ois = new ObjectInputStream(fis);
            List<StudentScore> scoreList = (List<StudentScore>) ois.readObject();
            ois.close();
            fis.close();
            return scoreList;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
